package com.yyge.controller.admin.product;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yyge.common.controller.BaseController;
import com.yyge.common.enums.AckCode;
import com.yyge.common.util.WaimaiThreadLocal;
import com.yyge.common.vo.resp.PageResp;
import com.yyge.common.vo.resp.R;
import com.yyge.config.DishFlavorConfig;
import com.yyge.controller.admin.login.resp.AdminLoginResp;
import com.yyge.controller.admin.mapstruct.ProductConverter;
import com.yyge.controller.admin.product.dto.DishFlavorProperty;
import com.yyge.controller.admin.product.req.ProductAddReq;
import com.yyge.controller.admin.product.req.ProductReq;
import com.yyge.controller.admin.product.resp.ProductResp;
import com.yyge.entity.DishFlavor;
import com.yyge.entity.Product;
import com.yyge.service.DishFlavorService;
import com.yyge.service.ProductService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

@RestController
@RequestMapping("/api/product")
public class ProductController extends BaseController<Product,Object> {
    public ProductController() {
        this.converter=ProductConverter.class;
    }
    // 注入业务逻辑层
    private ProductService service;

    /*注入口味表的service*/
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired/*自动装配*/
    public void setService(ProductService productService){
        this.service=productService;
    }

    @ApiOperation(value = "分页查询")
    @GetMapping("data")/* GET(SELECT): 查询 */
    public R get(@Valid ProductReq req) throws Exception  {
        AdminLoginResp adminLoginResp= WaimaiThreadLocal.getCurrent();
        //强制增强商家ID
        if(adminLoginResp.getType()==2){
            req.setMerchantId(adminLoginResp.getId());
        }

        // 将对象进行转换过滤无效条件
        PageResp pageResp = service.search(req);
        System.out.println("商品查询结果...");
        System.out.println(pageResp.getRows());
        return R.okHasData(pageResp);
    }

    @ApiOperation(value = "修改前查询")
    @GetMapping("{id}")/* GET(SELECT): 查询 */
    public R getById(@PathVariable("id") String id) throws Exception  {
        ProductReq productReq=new ProductReq();
        AdminLoginResp adminLoginResp= WaimaiThreadLocal.getCurrent();

        //强制增强商家ID
        if(adminLoginResp.getType()==2){
            productReq.setMerchantId(adminLoginResp.getId());
        }

        // 将对象进行转换过滤无效条件
        ProductResp product = service.searchById(productReq,id);

        return R.okHasData(product);
    }





    @ApiOperation("新增")
    @Transactional
    @PostMapping/* POST(CREATE): 新增&登陆 */
    public R post(@RequestBody @Valid ProductAddReq req){
        Product product=service.addProduct(req);
        System.out.println(product);
         boolean b =false;
        if(product!=null){

            //先删除原有的口味数据
            LambdaQueryWrapper<DishFlavor> deleteQueryWrapper=new LambdaQueryWrapper<>();
            deleteQueryWrapper.eq(DishFlavor::getDishId,product.getId());
            dishFlavorService.remove(deleteQueryWrapper);

            List<DishFlavorProperty> list = req.getDishFlavors();
            List<DishFlavor> dishFlavors=new ArrayList<>();
            AdminLoginResp user = WaimaiThreadLocal.getCurrent();
            Product product2req = ProductConverter.MAPPER.convert(req);
            QueryWrapper wrapper=new QueryWrapper<>(product2req);
            List<Product> list1 = service.list(wrapper);
            if(list1.size()==1){
                for (DishFlavorProperty property:list) {
                    DishFlavor dishFlavor=new DishFlavor();
                    dishFlavor.setName(property.getName());
                    String jsonStr = JSONUtil.toJsonStr(property.getValue());
                    dishFlavor.setValue(jsonStr);
                    dishFlavor.setCreateBy(user.getName());
                    dishFlavor.setCreateTime(new Date());
                    dishFlavor.setDishId(product.getId());
                    dishFlavors.add(dishFlavor);
                }
              b = dishFlavorService.saveBatch(dishFlavors);
            }
        }
        return b?R.ok("新增成功！"):R.error(AckCode.SYSTEM_SERVICE_ADD_ERROR);
    }

    @PutMapping/* POST(CREATE): 更新 */
    public R out(@RequestBody Product product){
        Boolean i=service.updateById(product);
        return i?R.ok("修改成功！"):R.error(AckCode.SYSTEM_SERVICE_MODIFY_ERROR);
    }

    @PatchMapping/* PUT(UPDATE): 部分更新 */
    public R patch(@RequestBody Product product){
        return null;
    }

    @DeleteMapping("/{id}")/* DELETE(DELETE): 删除&&批量删除 */
    public R delete(@PathVariable("id") Integer[] list){
        boolean i = service.removeByIds(Arrays.asList(list));
        return i?R.ok("修改成功！"):R.error(AckCode.SYSTEM_SERVICE_DELETE_ERROR);
    }

    @ApiOperation(value = "口味列表数据")
    @GetMapping(value = "/dishflavor")
    public R<List<DishFlavorProperty>> dishFlavorData(){
        Map entries=this.redisTemplate.opsForHash().entries(DishFlavorConfig.DISHFLAVOR_KEY);
        Collection<DishFlavorProperty> values=entries.values();
        List<DishFlavorProperty> arr=new ArrayList<>(values);
        return R.okHasData(arr);
    }


//    @ApiOperation(value = "口味列表数据")
//    @GetMapping(value = "/isgrounding?status=0&ids=8")
//    public R<List<DishFlavorProperty>> dishFlavorData(){
//        Map entries=this.redisTemplate.opsForHash().entries(DishFlavorConfig.DISHFLAVOR_KEY);
//        Collection<DishFlavorProperty> values=entries.values();
//        List<DishFlavorProperty> arr=new ArrayList<>(values);
//        return R.okHasData(arr);
//    }

}

